const express = require("express");
const server = express();
const mysql = require("mysql");
const pool = mysql.createPool({
  host: "127.0.0.1",
  port: 3306,
  user: "root",
  password: "",
  database: "bestMobile",
  charset: "utf8",
  connectionLimit: 20,
});
const cors = require("cors");
server.use(
  cors({
    origin: ["http://127.0.0.1:5500", "http://localhost:5500"],
  })
);
const bodyParser = require("body-parser");
server.use(
  bodyParser.urlencoded({
    extended: false,
  })
);
server.listen(3000, () => {
  console.log("server is running...");
});

server.get("/", (req, res) => {
  let sql =
    "SELECT lid,l_name,title,price,detail,sales,shelfTime,isOnsale,categoryId,spec,imgSrc FROM mobile_laptop";
  pool.query(sql, (err, results) => {
    if (err) throw err;
    res.send({ message: "查询成功", code: 1, results: results });
    console.log(results);
  });
});

server.post("/register", (req, res) => {
  let obj = req.body;
  let params = {
    phone: req.body.phone,
    upwd: req.body.upwd,
  };
  let sql = "select uid,phone from mb_user where phone=?";
  pool.query(sql, [obj.phone], (err, result) => {
    if (err) throw err;
    console.log(result);
    if (result.length < 1) {
      let insert = "insert into mb_user set ?";
      pool.query(insert, [params], (err, results) => {
        if (err) throw err;
        res.send({ code: 200, results: results });
      });
    } else {
      res.send({ code: 400, message: "手机号已经存在" });
    }
  });
});

server.post("/login", (req, res) => {
  let obj = req.body;
  let params = {
    phone: obj.phone,
    upwd: obj.upwd,
  };
  let sql = "select ? from mb_user";
  pool.query(sql, [params], (err, result) => {
    if (err) throw err;
    res.send({ code: 200, message: "登录成功" });
  });
});

server.get("/list", (req, res) => {
  // 当前页数
  let param = parseInt(req.query.id);
  console.log(param);
  //   计算开始查询的值
  let c = (param - 1) * 5;
  let sql = "select tid,title,detail,price,count,lg,sm from mb_list limit ?,5";
  pool.query(sql, [c], (err, result) => {
    if (err) throw err;
    res.send({ code: 200, message: "查询成功", result: result });
  });
});
